import prompt from '@system.prompt';
import { User } from '../db/User'
import RdbUtils from './RdbUtils'
import { relationalStore } from '@kit.ArkData';

class UserAPI {
  private STORE_CONFIG: relationalStore.StoreConfig = {
    name: 'my.db',
    securityLevel: relationalStore.SecurityLevel.S3
  }
  private tableName: string = ''
  private columns: Array<string> = []
  private sql_create_table = ''

  constructor() {
    this.tableName = 'user'
    this.columns = ['id', 'name', 'sex', 'age', 'tel']
    this.sql_create_table = 'CREATE TABLE IF NOT EXISTS '
      + this.tableName + '('
      + 'id INTEGER PRIMARY KEY AUTOINCREMENT, '
      + 'name TEXT NOT NULL, '
      + 'sex TEXT, '
      + 'age INTEGER, '
      + 'tel TEXT)';
  }
  // 获取rdbStore
  getRdbStore(context)
  {
    relationalStore.getRdbStore(context, this.STORE_CONFIG, (err, rdbStore) => {
      if (err) {
        console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);
        return;
      }
      console.info(`Succeeded in getting RdbStore.`);
      // 1. 创建数据库
      RdbUtils.setStore(rdbStore);
      // 2. 执行sql语句
      RdbUtils.executeSql(this.sql_create_table).then(() => {
        prompt.showToast({ message: "创建成功！" })
      })
    });
  }
  // 插入数据
  insertUser(user) {
    const valueBucket = JSON.parse(JSON.stringify(user));
    RdbUtils.getStore().insert(this.tableName, valueBucket, function (err, ret) {
      prompt.showToast({ message:'insert done: ' + ret});
    });
  }

  // 根据用户名查询用户信息
  async queryUserByName(name) {
    let resultList;
    let predicates = new relationalStore.RdbPredicates(this.tableName);
    predicates.equalTo('name', name);
    let ret = await this.queryFromDB(predicates);
    resultList = this.getListFromResultSet(ret);
    return resultList;
  }

  // 查询全部用户信息
  async queryUserAll() {
    let resultList;
    let predicates = new relationalStore.RdbPredicates(this.tableName);
    let ret = await this.queryFromDB(predicates);
    resultList = this.getListFromResultSet(ret);
    return resultList;
  }

  // 根据条件查询数据库
  async queryFromDB(predicates) {
    let resultList;
    let promiseQuery = RdbUtils.getStore().query(predicates, this.columns);
    await promiseQuery.then((resultSet) => {
      resultList = resultSet;
    }).catch((err) => {
      prompt.showToast({ message:"query err" + JSON.stringify(err)});
    });
    return resultList;
  }

  // 将查询到的结果封装用户列表
  getListFromResultSet(resultSet) {
    let userList = [];
    for (let i = 0; i < resultSet.rowCount; i++) {
      resultSet.goToNextRow();
      let user = new User(resultSet.getDouble(resultSet.getColumnIndex('id')),
        resultSet.getString(resultSet.getColumnIndex('name')),
        resultSet.getString(resultSet.getColumnIndex('sex')),
        resultSet.getString(resultSet.getColumnIndex('age')),
        resultSet.getString(resultSet.getColumnIndex('tel')));
      userList.push(user);
    }
    return userList;
  }

  // 删除全部数据
  async deleteAll() {
    let result
    let predicates = new relationalStore.RdbPredicates(this.tableName);
    await RdbUtils.getStore().delete(predicates).then((rows) => {
      result = rows;
      prompt.showToast({ message: '删除数据，rows:' + rows });
    });
    return result
  }

  // 更新数据，暂时未使用
  updateUser(user) {
    const valueBucket = JSON.parse(JSON.stringify(user));
    let predicates = new relationalStore.RdbPredicates(this.tableName);
    predicates.equalTo('id', user.id);
    RdbUtils.getStore().update(valueBucket, predicates, function (err, ret) {
      prompt.showToast({ message: '更新数据，ret:' + ret });
    });
  }

  // 删除数据，暂时未使用
  deleteUserById(userId) {
    let predicates = new relationalStore.RdbPredicates(this.tableName);
    predicates.equalTo('id', userId);
    RdbUtils.getStore().delete(predicates, function (err, rows) {
      prompt.showToast({ message: '删除数据，rows::' + rows });
    });
  }
}

export default UserAPI

